"use client"

import { notFound } from "next/navigation"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { ArrowLeft, Save, X } from "lucide-react"
import { useEffect, useState } from "react"
import { useToast } from "@/hooks/use-toast"
import { Sidebar } from "@/components/sidebar"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

interface Device {
  设备表及材料表中的实体对象名称: string
  对应的对象分类标准中的中文名称: string
  序号: number
  分类码: string
  对象命名: string
  位置信息: string
  基础参数: string
  技术规格书: string
  备注?: string
}

interface DeviceDetailPageProps {
  deviceId?: number  // Made optional since we now use device type code
  deviceName: string
  deviceData?: Device[]
  specialtyName: string
  specialtyRoute: string
  defaultTab?: string
}

// 模拟表格数据
const createMockTableData = (deviceName: string, tableType: string) => {
  const baseData = [
    { 属性: "设备编号", 值: "", 类型: "文本", 必填: true },
    { 属性: "设备名称", 值: deviceName, 类型: "文本", 必填: true },
    { 属性: "规格型号", 值: "", 类型: "文本", 必填: false },
    { 属性: "材质", 值: "", 类型: "选择", 必填: false },
    { 属性: "制造商", 值: "", 类型: "文本", 必填: false },
  ]

  if (tableType === "naming") {
    return [
      ...baseData,
      { 属性: "命名规则", 值: "", 类型: "文本", 必填: true },
      { 属性: "标识符", 值: "", 类型: "文本", 必填: true },
      { 属性: "版本号", 值: "1.0", 类型: "文本", 必填: false },
    ]
  } else if (tableType === "location") {
    return [
      ...baseData,
      { 属性: "装置区域", 值: "", 类型: "选择", 必填: true },
      { 属性: "工艺单元", 值: "", 类型: "选择", 必填: true },
      { 属性: "建筑物", 值: "", 类型: "文本", 必填: false },
      { 属性: "楼层", 值: "", 类型: "数字", 必填: false },
      { 属性: "房间号", 值: "", 类型: "文本", 必填: false },
      { 属性: "坐标X", 值: "", 类型: "数字", 必填: false },
      { 属性: "坐标Y", 值: "", 类型: "数字", 必填: false },
    ]
  } else if (tableType === "parameters") {
    return [
      ...baseData,
      { 属性: "额定功率", 值: "", 类型: "数字", 必填: false },
      { 属性: "工作压力", 值: "", 类型: "数字", 必填: false },
      { 属性: "工作温度", 值: "", 类型: "数字", 必填: false },
      { 属性: "介质", 值: "", 类型: "文本", 必填: false },
      { 属性: "连接方式", 值: "", 类型: "选择", 必填: false },
      { 属性: "密封等级", 值: "", 类型: "选择", 必填: false },
    ]
  }

  return baseData
}

type ParamType = 'naming' | 'position' | 'base'
type ParamRow = { id: number; parameter_name: string; parameter_value: string; data_type?: string; is_required?: boolean; example_description?: string; measurement_class?: string; measurement_unit?: string; data_source?: string }

export default function DeviceDetailPage({
  deviceId,
  deviceName,
  deviceData,
  specialtyName,
  specialtyRoute,
  defaultTab = "naming"
}: DeviceDetailPageProps) {
  const { toast } = useToast()
  const device = deviceData?.find((d) => d.设备表及材料表中的实体对象名称 === deviceName)
  const [tab, setTab] = useState(defaultTab)
  const [parameters, setParameters] = useState<Record<ParamType, ParamRow[]>>({
    naming: [],
    position: [],
    base: []
  })
  const [loading, setLoading] = useState(false)
  const [changed, setChanged] = useState<Record<ParamType, boolean>>({
    naming: false,
    position: false,
    base: false
  })
  const [editData, setEditData] = useState<Record<ParamType, Record<number, string>>>({
    naming: {},
    position: {},
    base: {}
  })
  
  // 新增状态：实例列表和当前选中的实例
  const [instances, setInstances] = useState<any[]>([])
  const [selectedInstanceId, setSelectedInstanceId] = useState<number | null>(null)

  // 加载实例列表
  const fetchInstances = async () => {
    try {
      const deviceTypeCode = device?.分类码
      console.log('[调试] 开始加载实例列表，设备:', deviceName, '分类码:', deviceTypeCode)
      
      if (!deviceTypeCode) {
        console.error('设备类型代码未找到:', deviceName)
        return
      }

      const apiUrl = `/api/device-instances?deviceTypeCode=${deviceTypeCode}`
      console.log('[调试] API调用:', apiUrl)
      
      const res = await fetch(apiUrl)
      const result = await res.json()
      
      console.log('[调试] API响应成功:', result.success, '实例数量:', result.data?.length || 0)
      
      if (result.success && result.data && result.data.length > 0) {
        setInstances(result.data)
        // 默认选择第一个实例并立即加载其参数
        if (!selectedInstanceId && result.data.length > 0) {
          const firstInstanceId = result.data[0].id
          console.log('[调试] 默认选择第一个实例:', firstInstanceId)
          setSelectedInstanceId(firstInstanceId)
          
          // 手动加载第一个实例的参数数据，避免useEffect循环
          setTimeout(() => {
            loadParametersForInstance(result.data[0])
          }, 0)
        }
      } else {
        console.log('[调试] 未找到实例数据或API失败')
        setInstances([])
        setSelectedInstanceId(null)
      }
    } catch (e) {
      console.error('[调试] 加载实例列表失败:', e)
      setInstances([])
      setSelectedInstanceId(null)
    }
  }

  // 防止重复加载的状态
  const [isLoadingParams, setIsLoadingParams] = useState(false)
  
  // 直接为指定实例加载参数
  const loadParametersForInstance = (instance: any) => {
    // 防止重复加载
    if (isLoadingParams) {
      console.log(`[调试] 正在加载中，跳过重复请求`)
      return
    }
    
    setIsLoadingParams(true)
    console.log(`[调试] 为实例 ${instance.object_number} 加载参数`)
    
    try {
      // 批量更新所有参数状态，避免多次setState
      const newParameters: Record<ParamType, ParamRow[]> = {
        naming: [],
        position: [],
        base: []
      }
      const newEditData: Record<ParamType, Record<number, string>> = {
        naming: {},
        position: {},
        base: {}
      }
      const newChanged: Record<ParamType, boolean> = {
        naming: false,
        position: false,
        base: false
      }
      
      (['naming', 'position', 'base'] as const).forEach(type => {
        const paramTypeMap = {
          'naming': 'naming',
          'position': 'position', 
          'base': 'base_params'
        } as const
        
        const paramData = instance.parameters[paramTypeMap[type]] || {}
        
        const data = Object.entries(paramData).map(([key, value], index) => ({
          id: index + 1,
          parameter_name: key,
          parameter_value: value || '',
          data_type: typeof value === 'number' ? '数值型' : '文本型',
          is_required: false,
          example_description: '',
          measurement_class: '',
          measurement_unit: '',
          data_source: 'E'
        }))

        newParameters[type] = data
        
        // 初始化编辑数据
        const editObj: Record<number, string> = {}
        data.forEach((p: any) => { editObj[p.id] = p.parameter_value || "" })
        newEditData[type] = editObj
        
        console.log(`[调试] ${type}参数: ${data.length}条记录`)
      })
      
      // 一次性更新所有状态
      setParameters(newParameters)
      setEditData(newEditData)
      setChanged(newChanged)
      
      console.log(`[调试] 实例 ${instance.object_number} 参数加载完成`)
    } catch (error) {
      console.error('[调试] 加载参数时出错:', error)
    } finally {
      setIsLoadingParams(false)
    }
  }

  // 保存实例参数（暂时显示提示信息）
  const handleSave = async (type: ParamType) => {
    setLoading(true)
    try {
      // 实例数据保存功能需要完整的实例管理系统
      toast({ 
        title: "功能开发中", 
        description: `${type}参数保存功能正在开发中` 
      })
    } catch (e) {
      console.error(`保存${type}参数失败:`, e)
      toast({ title: "保存失败", description: `保存${type}参数失败` })
    } finally {
      setLoading(false)
    }
  }

  // 首先加载实例列表
  useEffect(() => {
    if (device?.分类码) {
      console.log('[调试] 组件初始化，加载实例列表')
      // 确保loading状态正确重置
      setLoading(false)
      setIsLoadingParams(false)
      fetchInstances()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [device?.分类码]) // 只依赖分类码，避免整个device对象变化

  // 实例选择改变处理函数
  const handleInstanceChange = (instanceId: string) => {
    const newInstanceId = parseInt(instanceId)
    console.log('[调试] 用户选择实例:', newInstanceId)
    setSelectedInstanceId(newInstanceId)
    
    const selectedInstance = instances.find(inst => inst.id === newInstanceId)
    if (selectedInstance) {
      loadParametersForInstance(selectedInstance)
    }
  }

  // 处理输入
  const handleInput = (type: ParamType, id: number, value: string) => {
    setEditData((prev) => ({ ...prev, [type]: { ...prev[type], [id]: value } }))
    setChanged((prev) => ({ ...prev, [type]: true }))
  }


  // 渲染表格（区分base表结构）
  const renderTable = (type: ParamType, title: string, desc: string) => {
    // 判断是否基础参数表
    const isBase = type === 'base';
    
    // 获取当前选中实例的描述信息
    const currentInstance = instances.find(inst => inst.id === selectedInstanceId);
    const instanceInfo = currentInstance ? 
      `${currentInstance.instance_number} - ${currentInstance.object_number}` : '';
    
    return (
      <Card>
        <CardHeader className="blue-card-header">
          <CardTitle>
            {title}
            {instanceInfo && (
              <span className="ml-2 text-sm font-normal text-blue-200">
                (实例: {instanceInfo})
              </span>
            )}
          </CardTitle>
          <CardDescription>{desc}</CardDescription>
        </CardHeader>
        <CardContent className="pt-6">
          {console.log(`[调试] 渲染${type}表格，参数数量:`, parameters[type]?.length || 0, 'loading:', loading, 'isLoadingParams:', isLoadingParams)}
          <div className="rounded-md border blue-border shadow-sm bg-white overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full caption-bottom text-sm">
                <thead>
                  <tr className="blue-header">
                    {isBase ? (
                      <>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[60px]">序号</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[160px]">中文名称</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[180px]">示例或属性说明</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[80px]">数据类型</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[80px]">计量类</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[80px]">计量单位</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[100px]">数据来源</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[120px]">数据录入</th>
                      </>
                    ) : (
                      <>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[200px]">参数名称</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white">值</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[100px]">类型</th>
                        <th className="h-12 px-4 text-left align-middle font-medium text-white w-[80px]">必填</th>
                      </>
                    )}
                  </tr>
                </thead>
                <tbody>
                  {parameters[type] && parameters[type].length > 0 ? parameters[type].map((row: any, idx: number) => (
                    <tr key={row.id} className="border-b transition-colors blue-hover">
                      {isBase ? (
                        <>
                          <td className="p-4 align-middle">{idx + 1}</td>
                          <td className="p-4 align-middle">{row.parameter_name}</td>
                          <td className="p-4 align-middle">{row.example_description}</td>
                          <td className="p-4 align-middle">{row.data_type}</td>
                          <td className="p-4 align-middle">{row.measurement_class}</td>
                          <td className="p-4 align-middle">{row.measurement_unit}</td>
                          <td className="p-4 align-middle">{row.data_source}</td>
                          <td className="p-4 align-middle">
                            <Input
                              value={editData[type][row.id] ?? row.parameter_value ?? ""}
                              onChange={e => handleInput(type, row.id, e.target.value)}
                              placeholder="请输入数据"
                              className="w-full"
                            />
                          </td>
                        </>
                      ) : (
                        <>
                          <td className="p-4 align-middle font-medium">{row.parameter_name}</td>
                          <td className="p-4 align-middle">
                            <Input
                              value={editData[type][row.id] ?? row.parameter_value ?? ""}
                              onChange={e => handleInput(type, row.id, e.target.value)}
                              placeholder={`请输入${row.parameter_name}`}
                              className="w-full"
                            />
                          </td>
                          <td className="p-4 align-middle">
                            <Badge variant="outline" className="blue-badge">{row.data_type}</Badge>
                          </td>
                          <td className="p-4 align-middle">
                            {row.is_required ? (
                              <Badge variant="destructive" className="text-xs">必填</Badge>
                            ) : (
                              <Badge variant="secondary" className="text-xs">可选</Badge>
                            )}
                          </td>
                        </>
                      )}
                    </tr>
                  )) : (
                    <tr>
                      <td colSpan={isBase ? 8 : 4} className="p-8 text-center text-muted-foreground">
                        {isLoadingParams ? '正在加载参数数据...' : '暂无参数数据'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
          {changed[type] && (
            <div className="flex justify-end gap-2 mt-4">
              <Button variant="outline" onClick={() => {
                // 重置当前类型的编辑状态
                const originalData: Record<number, string> = {}
                parameters[type].forEach((p: any) => { originalData[p.id] = p.parameter_value || "" })
                setEditData((prev) => ({ ...prev, [type]: originalData }))
                setChanged((prev) => ({ ...prev, [type]: false }))
              }} disabled={loading}><X className="h-4 w-4 mr-2" />取消</Button>
              <Button onClick={() => handleSave(type)} disabled={loading}><Save className="h-4 w-4 mr-2" />{loading ? "保存中..." : "保存"}</Button>
            </div>
          )}
        </CardContent>
      </Card>
    );
  };

  if (!device) {
    notFound()
  }

  // Tab key严格用'naming'、'position'、'base'
  const tabList = [
    { key: 'naming', label: '对象命名表', title: '对象命名表', desc: '定义设备的命名规则和标识信息' },
    { key: 'position', label: '位置信息表', title: '位置信息表', desc: '记录设备的安装位置和空间信息' },
    { key: 'base', label: '基础参数表', title: '基础参数表', desc: '设备的技术参数和性能指标' },
  ];

  return (
    <div className="flex h-screen bg-gray-50">
      {/* 侧边栏 */}
      <Sidebar />

      {/* 主内容区域 */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <div className="flex-1 overflow-auto">
          <div className="container mx-auto py-8">
            {/* 返回链接 */}
            <div className="mb-6">
              <Link href={specialtyRoute === "valve" ? "/" : `/${specialtyRoute}`}>
                <Button variant="outline" className="gap-2">
                  <ArrowLeft className="h-4 w-4" />
                  返回{specialtyName}列表
                </Button>
              </Link>
            </div>

            {/* 页面标题 */}
            <div className="mb-8">
              <div className="flex items-center gap-4 mb-4">
                <h1 className="text-4xl font-bold text-primary">{device.设备表及材料表中的实体对象名称}</h1>
                <Badge className="blue-badge-solid">{specialtyName}</Badge>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm text-muted-foreground">
                <div>
                  <span className="font-medium">分类码:</span> 
                  <code className="ml-2 bg-muted px-2 py-1 rounded">{device.分类码}</code>
                </div>
                <div>
                  <span className="font-medium">序号:</span> {device.序号}
                </div>
                <div>
                  <span className="font-medium">对象分类:</span> {device.对应的对象分类标准中的中文名称}
                </div>
                <div>
                  <span className="font-medium">技术规格书:</span> {device.技术规格书}
                </div>
              </div>
            </div>

            {/* 实例选择器 */}
            {instances.length > 0 && (
              <div className="mb-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">设备实例选择</CardTitle>
                    <CardDescription>
                      该设备类型共有 {instances.length} 个实例，请选择要查看的具体实例
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="flex flex-col space-y-4">
                      <div className="flex items-center space-x-4">
                        <Label htmlFor="instance-select" className="min-w-0 flex-shrink-0">选择实例:</Label>
                        <Select
                          value={selectedInstanceId?.toString() || ""}
                          onValueChange={handleInstanceChange}
                        >
                          <SelectTrigger className="w-full max-w-md">
                            <SelectValue placeholder="请选择实例" />
                          </SelectTrigger>
                          <SelectContent>
                            {instances.map((instance) => (
                              <SelectItem key={instance.id} value={instance.id.toString()}>
                                {instance.instance_number} - {instance.object_number} ({instance.object_description})
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      
                      {/* 显示当前选中实例的详细信息 */}
                      {selectedInstanceId && instances.find(inst => inst.id === selectedInstanceId) && (
                        <div className="bg-muted p-4 rounded-lg">
                          <h4 className="font-medium mb-2">当前实例信息:</h4>
                          {(() => {
                            const currentInstance = instances.find(inst => inst.id === selectedInstanceId);
                            return currentInstance ? (
                              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                                <div>
                                  <span className="font-medium">实例号:</span> 
                                  <code className="ml-2 bg-background px-2 py-1 rounded">{currentInstance.instance_number}</code>
                                </div>
                                <div>
                                  <span className="font-medium">对象编号:</span> 
                                  <code className="ml-2 bg-background px-2 py-1 rounded">{currentInstance.object_number}</code>
                                </div>
                                <div className="md:col-span-2">
                                  <span className="font-medium">描述:</span> {currentInstance.object_description}
                                </div>
                              </div>
                            ) : null;
                          })()}
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              </div>
            )}

            {/* 标签页内容 */}
            <Tabs defaultValue={defaultTab} className="space-y-6" onValueChange={setTab}>
              <TabsList className="grid w-full grid-cols-3 blue-tabs">
                {tabList.map(tab => (
                  <TabsTrigger key={tab.key} value={tab.key} className="blue-tab-active">{tab.label}</TabsTrigger>
                ))}
              </TabsList>
              {tabList.map(tab => (
                <TabsContent key={tab.key} value={tab.key} className="space-y-6">
                  {renderTable(tab.key as ParamType, tab.title, tab.desc)}
                </TabsContent>
              ))}
            </Tabs>
          </div>
        </div>
      </div>
    </div>
  )
} 